import React, {useEffect, useState} from 'react';
import {Button, Empty, Flex, Form, GetProps, Input, Modal, Space, Table, Tag} from 'antd';
import type {TableColumnsType, TableProps} from 'antd';
import {addLinkAPI, deleteLinkAPI, getLinkDetailAPI, getLinkListAPI, updateLinkAPI} from "@api/Link";
import {message} from "antd/lib";
import {updateArticleAPI} from "@api/Article";

type SearchProps = GetProps<typeof Input.Search>;
const {Search} = Input;

// 定义表格数据类型
interface DataType {
    key: React.Key;
    icon: string;
    url: string;
    description: string,
    title: string,
    isValid: boolean
}

interface TableParams {
    page: number,
    pageSize: number,
    sort: {
        _id: number
    },
    filter: {
        title: {
            $regex: string,
            $options: string
        },
        isValid?: boolean
    }
}

type FieldType = {
    title?: string;
    icon?: string;
    url?: string;
    description?: string;
};

function FriendLinkManage() {
    type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];
    // 定义表格列表头
    const columns: TableColumnsType<DataType> = [
        {
            title: '图标',
            dataIndex: 'icon',
            render: (_, record) => (
                <img src={record.icon} alt={record.title} width={40} height={40}/>
            )
        },
        {title: '网站名称', dataIndex: 'title'},
        {
            title: '链接', dataIndex: 'url',
            render: (_, record) => (
                <a href={record.url} target="_blank" rel="noopener noreferrer">{record.url}</a>
            )
        },
        {title: '描述', dataIndex: 'description'},
        {
            title: '状态',
            dataIndex: 'isValid',
            width: 100,
            render: (_, record) => (
                record.isValid ? <Tag color="green">
                    启用
                </Tag> : <Tag color="red">
                    禁用
                </Tag>
            ),
            filters: [
                {text: '启用', value: true},
                {text: '禁用', value: false}
            ]
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 180,
            render: (_, records) => (
                <>
                    <Space>
                        <Button type="primary" onClick={() => editLink(records)}>编辑</Button>
                        <Button style={{background: "#fff1f0", color: '#cf1322', border: '#ffa39e 1px solid'}}
                                onClick={() => {deleteSimpleLink(records)}}>删除</Button>
                    </Space>
                </>
            
            )
        }
    ];
    const [dataSource, setDataSource] = useState<DataType[]>([])
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [selectRow, setSelectRow] = useState<boolean>(true)
    // 定义搜索框
    const [searchValue, setSearchValue] = useState<string>('');
    const [total, setTotal] = useState(0)
    const [linkID, setLinkID] = useState<string | null>(null)
    // 定义分页
    const [pageOptions, setPageOptions] = useState<TableParams>({
        page: 1,
        pageSize: 6,
        sort: {
            _id: 1
        },
        filter: {
            title: {
                $regex: searchValue,
                $options: 'i'
            }
        }
    });
    const [form] = Form.useForm();
    const axiosLinkList = async () => {
        try {
            const res = await getLinkListAPI(pageOptions)
            setTotal(res.data.data[0].total)
            setDataSource(res.data.data[1])
        } catch (error) {
            console.error("Error fetching article list:", error);
        }
    }
    const editLink = (row: any) => {
        // 打开编辑链接的弹窗
        setLinkID(row._id)
        // 获取当前链接详情
        getLinkDetailAPI(row._id).then((res) => {
            // 打开弹窗
            console.log(res.data.data)
            setIsModalOpen(true)
            // 设置表单值
            form.setFieldsValue(res.data.data)
        })
        showModal()
        
    }
    const deleteSimpleLink = (row: any) => {
        deleteLinkAPI(row._id).then((res) => {
            // 更新页码
            axiosLinkList()
            message.success(res.data.message)
        })
    }
    // 删除多个友链
    const deleteMoreLink = async () => {
        deleteLinkAPI(selectedRowKeys).then((res) => {
            // 更新页码
            setPageOptions({
                page: pageOptions.page,
                pageSize: pageOptions.pageSize,
                sort: {
                    _id: 1
                },
                filter: {
                    title: {
                        $regex: searchValue,
                        $options: 'i'
                    }
                }
            })
            axiosLinkList()
            message.success(res.data.message)
            // 清空选择行
            setSelectedRowKeys([])
            setSelectRow(true)
        })
    }
    
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
        setSelectRow(!(newSelectedRowKeys.length > 0))
    };
    // 选择行的配置
    const rowSelection: TableRowSelection<DataType> = {
        selectedRowKeys,
        onChange: onSelectChange
    };
    // 分页
    const changePageOption = (pageSize: number, current: number, isValid: any) => {
        // 如果 state 为空，说明没有筛选条件
        if (isValid === null) isValid = [true, false]
        setSelectedRowKeys([])
        setSelectRow(true)
        pageOptions.page = current as number
        setPageOptions({
            page: current as number,
            pageSize: pageSize as number,
            sort: {
                _id: 1
            },
            filter: {
                title: {
                    $regex: searchValue,
                    $options: 'i'
                },
                isValid
            }
        })
        axiosLinkList()
    }
    const onSearch: SearchProps['onSearch'] = (value, _e, info) => {
        setSearchValue(value)
        setPageOptions({
            page: 1,
            pageSize: 6,
            sort: {
                _id: 1
            },
            filter: {
                title: {
                    $regex: value,
                    $options: 'i'
                }
            }
        })
        axiosLinkList()
    }
    useEffect(() => {
        // 获取友链列表
        getLinkListAPI(pageOptions).then((res) => {
            setDataSource(res.data.data[1])
            setTotal(res.data.data[0].total)
        })
    }, [pageOptions.page, pageOptions.filter.title, pageOptions.filter.isValid]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    
    const showModal = () => {
        setIsModalOpen(true);
    };
    
    const handleOk = () => {
        // 处理表单提交逻辑
        if (linkID) {
            // 修改友链
            updateLinkAPI({...form.getFieldsValue(), id: linkID}).then((res) => {
                message.success(res.data.message)
            }).catch((err) => {
                message.error(err.response.data.message)
            })
        } else {
            // 添加友链
            addLinkAPI(form.getFieldsValue()).then((res) => {
                message.success(res.data.message)
            }).catch((err) => {
                message.error(err.response.data.message)
            })
        }
        setIsModalOpen(false);
        axiosLinkList()
        // 清空表单
        form.resetFields()
    };
    
    const handleCancel = () => {
        setLinkID(null)
        form.resetFields()
    };
    
    return (
        <>
            <Flex gap="middle" vertical>
                <Flex align="center" gap="middle">
                    <Button type="primary" onClick={showModal}>
                        添加友链
                    </Button>
                    <Modal title={linkID ? "编辑友链" : "添加友链"} open={isModalOpen} onOk={handleOk}
                           onCancel={() => {setIsModalOpen(false)}}
                           cancelText="清空表单"
                           okText={linkID ? "修改" : "添加"}>
                        <Form
                            form={form}
                            name="basic"
                            labelCol={{span: 4}}
                            wrapperCol={{span: 20}}
                            style={{maxWidth: 600, marginTop: 20}}
                            autoComplete="off"
                        >
                            <Form.Item<FieldType>
                                label="网站图标"
                                name="icon"
                                rules={[{required: true, message: '请输入图标链接!'}]}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item<FieldType>
                                label="网站名称"
                                name="title"
                                rules={[{required: true, message: '请输入网站名称!'}]}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item<FieldType>
                                label="网站链接"
                                name="url"
                                rules={[{required: true, message: '请输入网站链接!'}]}
                            >
                                <Input/>
                            </Form.Item>
                            <Form.Item<FieldType>
                                label="网站描述"
                                name="description"
                                rules={[{required: true, message: '请选择文章分类!'}]}
                            >
                                <Input/>
                            </Form.Item>
                        </Form>
                    </Modal>
                    <Button danger disabled={selectRow} onClick={() => {deleteMoreLink()}}>删除所选</Button>
                    <Search placeholder="请输入搜索内容" onSearch={onSearch} enterButton style={{width: 300}}/>
                </Flex>
                <Table<DataType> rowSelection={rowSelection} columns={columns} dataSource={dataSource}
                                 rowKey="_id"
                                 pagination={{
                                     total,
                                     pageSize: pageOptions.pageSize,
                                     showSizeChanger: false,
                                     showTotal: (total) => `共 ${total} 条`
                                 }}
                                 onChange={({pageSize, current}, {isValid}) => {
                                     changePageOption(pageSize as number, current as number, isValid)
                                 }}
                                 locale={{emptyText: <Empty description="没有相关数据哦"></Empty>}}
                />
            
            </Flex>
        </>
    )
        ;
}

export default FriendLinkManage;